package com.imooc.product.service.impl;

import com.imooc.product.common.DecreaseStockInput;
import com.imooc.product.common.ProductInfoOutput;
import com.imooc.product.dataobject.ProductInfo;
import com.imooc.product.dto.CartDTO;
import com.imooc.product.enums.ProductStatusEnum;
import com.imooc.product.enums.ResultEnum;
import com.imooc.product.exception.ProductException;
import com.imooc.product.repository.ProductInfoRepository;
import com.imooc.product.service.ProductInfoService;
import com.imooc.product.util.JsonUtil;
import com.rabbitmq.tools.json.JSONUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author steve
 * @date 2020/6/15 14:02
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {

    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public void decrease(List<DecreaseStockInput> decreaseStockInputList) {
        //整个购物车处理流程
        List<ProductInfo> productInfoList = decreaseProcess(decreaseStockInputList);

        //购物车流程处理完后，发送消息到mq
        //需要把productInfo转换成productInfoOutput
        List<ProductInfoOutput> productInfoOutputList = productInfoList.stream().map(e -> {
                    ProductInfoOutput output = new ProductInfoOutput();
                    BeanUtils.copyProperties(e, output);
                    return output;
                }).collect(Collectors.toList());
        amqpTemplate.convertAndSend("productInfo", JsonUtil.toJson(productInfoOutputList));
    }

    /**
     * 处理整个购物车流程
     * @param decreaseStockInputList
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<ProductInfo> decreaseProcess(List<DecreaseStockInput> decreaseStockInputList) {
        List<ProductInfo> productInfoList = new ArrayList<>();
        for (DecreaseStockInput decreaseStockInput : decreaseStockInputList) {
            //从购物车信息获取商品
            Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(decreaseStockInput.getProductId());
            if (!productInfoOptional.isPresent()) {
                //商品不存在
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            ProductInfo productInfo = productInfoOptional.get();
            if (productInfo.getProductStock() < 0) {
                //商品库存小于0，商品不存在
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR_DB);
            }
            //获取购买以后商品库存
            int stockNum = productInfo.getProductStock() - decreaseStockInput.getProductQuantity();

            if (stockNum < 0) {
                //商品库存不足于本次购买
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            //商品重新设置库存数量(扣库存)
            productInfo.setProductStock(stockNum);
            productInfoList.add(productInfo);
            //存入数据库
            productInfoRepository.save(productInfo);
        }
        return productInfoList;
    }

    @Override
    public List<ProductInfoOutput> listForOrder(List<String> productIdList) {
        List<ProductInfoOutput> productInfoOutputList = new ArrayList<>();
        for (String productId : productIdList) {
            ProductInfo productInfo = productInfoRepository.findById(productId).get();
            ProductInfoOutput productInfoOutput = new ProductInfoOutput();
            BeanUtils.copyProperties(productInfo, productInfoOutput);
            productInfoOutputList.add(productInfoOutput);
        }
        return productInfoOutputList;
    }
}
